package cn.lili.modules.permission.serviceimpl;

import cn.lili.modules.permission.entity.dos.RoleMenu;
import cn.lili.modules.permission.entity.vo.UserMenuVO;
import cn.lili.modules.permission.mapper.MenuMapper;
import cn.lili.modules.permission.mapper.RoleMenuMapper;
import cn.lili.modules.permission.service.RoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色菜单业务层实现
 *
 * @author Chopper
 * @since 2020/11/22 11:43
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    /**
     * 菜单
     */
    private final MenuMapper menuMapper;


    @Override
    public List<RoleMenu> findByRoleId(String roleId) {
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, roleId);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<UserMenuVO> findAllMenu(String userId) {
        return menuMapper.getUserRoleMenu(userId);
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateRoleMenu(String roleId, List<RoleMenu> roleMenus) {
        //删除角色已经绑定的菜单
        this.deleteRoleMenu(roleId);
        if (roleMenus != null && !roleMenus.isEmpty()) {
            roleMenus.forEach(roleMenu -> {
                roleMenu.setRoleId(roleId);
            });

            //重新保存角色菜单关系
            this.saveBatch(roleMenus);
        }
    }

    @Override
    public void deleteRoleMenu(String roleId) {
        //删除
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        this.remove(queryWrapper);
    }

    @Override
    public void deleteRoleMenu(List<String> roleIds) {
        //删除
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id", roleIds);
        this.remove(queryWrapper);

    }

    @Override
    public List<RoleMenu> getRoleMenuByMenuIds(List<String> menuIds) {
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("menu_id", menuIds);
        return this.list(queryWrapper);
    }
}